package com.bosssoft.common.core.filter;

import com.bosssoft.common.context.UserBaseContextHolder;
import com.bosssoft.common.context.UserInfo;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                UserInfo userInfo = TokenUtil.getUserInfoFromToken(token);
                UserBaseContextHolder.setUser(userInfo);
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Token");
                return;
            }
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            UserBaseContextHolder.clearUser();
        }
    }
}
